package com.nari.temperature.action;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import org.json.JSONArray;

import com.nari.baseinfo.model.IBuilding;
import com.nari.baseinfo.model.IHeatMeter;
import com.nari.baseinfo.service.IBaseStatisService;
import com.nari.baseinfo.service.IBuildingService;
import com.nari.baseinfo.service.ICommunityService;
import com.nari.baseinfo.service.IHeatMeterService;
import com.nari.baseinfo.utils.statisentity.BuildingStatisEntity;
import com.nari.coreframe.action.struts2.JSONActionSupport;
import com.nari.heatshare.model.IHeatMeterDataGather;
import com.nari.heatshare.model.ITemperaturePoint;
import com.nari.heatshare.model.ITemperaturePointDataGather;
import com.nari.heatshare.service.IHeatMeterDataGatherService;
import com.nari.heatshare.service.ITemperaturePointDataGatherService;
import com.nari.heatshare.service.ITemperaturePointService;
import com.nari.platform.model.PageCond;
import com.nari.platform.model.ResultWithPageCond;
import com.nari.temperature.po.TemperatureHousePojo;
import com.nari.temperature.po.TemperatureMeterDataPojo;
import com.nari.temperature.service.FavFTPUtil;



public class TemperatureAction extends JSONActionSupport{
	private static final long serialVersionUID = -4382890629206238461L;
	//温度点信息service
	private ITemperaturePointService iTemperaturePointService;
	//温度点数据service
	private ITemperaturePointDataGatherService iTemperaturePointDataGatherService;
	//热量表信息service
	private IHeatMeterDataGatherService iHeatMeterDataGatherService;
	//热量表数据service
	private IHeatMeterService iHeatMeterService;
	private IBaseStatisService iBaseStatisService;
	
	private IBuildingService iBuildingService;
	private ICommunityService iCommunityService;
	
	private String projectUID;
	private String communityUID;
	private String buildingUID;
	private Date recordDate;
	private static String filetreeNodeName;
	private static String projectNameString;
	
	private String seriousNum;
	private String concentratorUID;
	private String concentratorNo;
	private String shareAreaUID;
	private PageCond pageCond;
	
	private String meterNo;
	private String meterNo1;
	private String meterNo2;
	private Date recordTime;
	private Date recordTimeStart;
	private Date recordTimeEnd;
	
	private String pointData;
	
	private List<TemperatureMeterDataPojo> tempMeterList;
	private List<String> commtList;
	private List<String> houseDateList;
	private double roomHeatAreaSum;
	
//	private FavFTPUtil favFTPUtil;
	private String hostname;
	private int port;
	private String username;
	private String password;
	private String pathname;
	private String localpath;
	private String str;
	private String roomHeatDate;
	
	/**
	 * 跳转弹出能耗监测窗口
	 * @return
	 * @throws Exception
	 */
	public String queryTemperaturePage() throws Exception {
		return "temperaturePage";
	}
	

	/**
	 * 根据项目、小区、楼栋、查询时间，显示楼栋24小时能耗监控页面
	 * @return
	 * @throws Exception
	 */
	public String queryTemperaturePointPage() throws Exception {
		
		try {
			this.pageCond = new PageCond(); 
			//获取温度点的信息
			ResultWithPageCond<ITemperaturePoint> tempPointPage = this.iTemperaturePointService.queryTempPointPage(null, projectUID, communityUID, buildingUID, null, pageCond);
			List<ITemperaturePoint> list = tempPointPage.getList();
			//获取温度点数据
			List<TemperatureHousePojo> topList = queryHouseValue(list);
			tempMeterList = new ArrayList<TemperatureMeterDataPojo>();
			//获取热量表信息
			List<IHeatMeter> queryMetersByBelongs = this.iHeatMeterService.queryMetersByBelongs(projectUID, communityUID, buildingUID, shareAreaUID);
			queryHeatMeters(queryMetersByBelongs);
			BuildingStatisEntity queryBuildingStatisByID = iBaseStatisService.queryBuildingStatisByID(buildingUID);
			roomHeatAreaSum = queryBuildingStatisByID.getRoomHeatAreaSum();
			//获取热量表数据
			//将热量表数据封装进自定义po类中
			//将温度点数据转为json格式
			JSONArray jsonArray = new JSONArray(topList);
			pointData = jsonArray.toString();
			JSONArray roomHeat = new JSONArray(tempMeterList);
			roomHeatDate = roomHeat.toString();
			System.out.println(roomHeatDate);
			return "tempPointPage";
		} catch (Exception e) {
		}
		return "tempPointPage";
	}
	

	private void filldata(List<IHeatMeterDataGather> meterDateList) {
		TemperatureMeterDataPojo tempMeter;
		for (IHeatMeterDataGather tempeData : meterDateList) {
			tempMeter = new TemperatureMeterDataPojo();
			tempMeter.setMeterNo(tempeData.getMeterNo());
			tempMeter.setSumHeat(tempeData.getSumHeat());
			tempMeter.setSumHeatUnit(tempeData.getSumHeatUnit());
			tempMeter.setSumFlow(tempeData.getSumFlow());
			tempMeter.setSumFlowUnit(tempeData.getSumFlowUnit());
			tempMeter.setInstantPower(tempeData.getInstantPower());
			tempMeter.setHeatPower(tempeData.getHeatPower());
			tempMeter.setHeatPowerUnit(tempeData.getHeatPowerUnit());
			tempMeter.setSupplyTemperature(tempeData.getSupplyTemperature());
			tempMeter.setBackTemperature(tempeData.getBackTemperature());
			tempMeter.setTemperatureDiff(tempeData.getTemperatureDiff());
			tempMeter.setInstantFlow(tempeData.getInstantFlow());
			tempMeter.setInstantFlowUnit(tempeData.getInstantFlowUnit());
			tempMeterList.add(tempMeter);
			tempMeter = null;
		}
	        
	}



	/**
	 * 获取到温度点数据中的Hour*Value数据并封装进TemperatureHousePojo中
	 */
	private void methodGet(TemperatureHousePojo tpo,
			ITemperaturePointDataGather iTDateGather, ArrayList<Double> temps)
			throws NoSuchMethodException, IllegalAccessException,
			InvocationTargetException {
		//反射的方式进行获取温度点数据的字节码文件
		Class<ITemperaturePointDataGather> tempc =  ITemperaturePointDataGather.class;
		for(int i =0;i<24;i++){
			Method method = tempc.getMethod("getHour"+i+"Value", null);
			Double invoke = (Double) method.invoke(iTDateGather, null);
			temps.add(invoke);
		}
		tpo.setTemp(temps);
		
	}

	
	
	/**
	 * 格式化小数点显示位数
	 * @param s
	 * @return
	 */
	public String formatDouble(double s){
	      DecimalFormat fmt = new DecimalFormat("#.##");
	      return fmt.format(s);

	  }

	
	/**
	 * 小区能耗监测
	 * @return
	 * @throws Exception
	 */
	public String queryCommunityPointPage() throws Exception {
		try {
			this.pageCond = new PageCond();
			this.recordTime = this.recordDate;
			
			tempMeterList = new ArrayList<TemperatureMeterDataPojo>();
			commtList = new ArrayList<String>();
//		List<IHeatMeterDataGather> meterDateList = null;
			List<IBuilding> queryBuilding = this.iBuildingService.queryBuildingByBelongings(projectUID, communityUID);
			for (int i = 0; i < queryBuilding.size();i++) {
			    //获取热量表信息
				List<IHeatMeter> queryMetersByBelongs = this.iHeatMeterService.queryMetersByBelongs(projectUID, communityUID, queryBuilding.get(i).getId(), shareAreaUID);
				queryHeatMeters(queryMetersByBelongs);
				
				JSONArray jsonArraysArray = new JSONArray(tempMeterList);
				String jsonA = "{'buildingName':'"+queryBuilding.get(i).getBuildingName()+"','buildingValue':"+jsonArraysArray+"}";
				
				commtList.add(jsonA);
				JSONArray jsonArrayList = new JSONArray(commtList);
				jsonArrayList.toString();
				tempMeterList = new ArrayList<TemperatureMeterDataPojo>();
			}
			//获取温度点24小时温度
			ResultWithPageCond<ITemperaturePoint> tempPointPage = null;
			houseDateList = new ArrayList<String>();
			for (int i = 0; i < queryBuilding.size();i++) {
				tempPointPage = this.iTemperaturePointService.queryTempPointPage(null, projectUID, communityUID, queryBuilding.get(i).getId(), null, pageCond);
				List<ITemperaturePoint> list = new ArrayList<ITemperaturePoint>();
				list = tempPointPage.getList();
				//获取温度点数据
				List<TemperatureHousePojo> topList = queryHouseValue(list);
				ArrayList<Double> temp = null;
				ArrayList<Double> temps = new ArrayList<Double>();
				List<String> houseValues = null;
				for (int j = 0; j < topList.size(); j++) {
					if(topList.get(j).getTemp() != null){
						temp = new ArrayList<Double>();
						temp = topList.get(j).getTemp();
						Double double1 = 0.0D;
						Double double2 = 0.0D;
						int cunt = 0;
						for (int x = 0; x < temp.size(); x++) {
							if(temp.get(x) != null){
								double2 = temp.get(x);
								double1 += double2;
								cunt++;
							}
						}
						temps.add(double1 / cunt);
					}else{
						temps.add(0.0);
					}
				}
				Double aDouble = 0D;
				for (Double double1 : temps) {
					aDouble += double1;
				}
				Double buildHouseValue = aDouble / temps.size();
				String formatDouble = formatDouble(buildHouseValue);
				houseValues = new ArrayList<String>();
				houseValues.add(formatDouble);
				JSONArray array = new JSONArray(houseValues);
				String houseJsonString = "{'buildingName':'"+queryBuilding.get(i).getBuildingName()+"','houseValue':"+array+"}";
				houseDateList.add(houseJsonString);
			}
			JSONArray jsonArrayList = new JSONArray(houseDateList);
			jsonArrayList.toString();
			downloadFiles();
		return "communityTemp";
		} catch (Exception e) {
		}
		return "communityTemp";
}


	/**
	 * 获取热量表数据
	 * @param queryMetersByBelongs
	 * @throws Exception
	 */
	private void queryHeatMeters(List<IHeatMeter> queryMetersByBelongs)
			throws Exception {
		List<IHeatMeterDataGather> meterDateList;
		if(queryMetersByBelongs!=null&&queryMetersByBelongs.size()>0){
			IHeatMeter heatMeter1 = queryMetersByBelongs.get(0);
			this.meterNo1 = heatMeter1.getMeterNo();
			if(meterNo1!=null){
				ResultWithPageCond<IHeatMeterDataGather> queryMeterDataPage = this.iHeatMeterDataGatherService.queryMeterDataPage(this.meterNo1, recordTime, pageCond);
				meterDateList = queryMeterDataPage.getList();
				filldata(meterDateList);
			}
		}
		if(queryMetersByBelongs.size()>1){
			IHeatMeter heatMeter2 = queryMetersByBelongs.get(1);
			this.meterNo2 = heatMeter2.getMeterNo();
			if(meterNo2!=null){
				ResultWithPageCond<IHeatMeterDataGather> queryMeterDataPage = this.iHeatMeterDataGatherService.queryMeterDataPage(this.meterNo2, recordTime, pageCond);
				meterDateList = queryMeterDataPage.getList();
				filldata(meterDateList);
			}
		}
	}

	
	
	
	
	/**
	 * 获取温度点编号及数据
	 */
	private List<TemperatureHousePojo> queryHouseValue(
			List<ITemperaturePoint> list) throws Exception,
			NoSuchMethodException, IllegalAccessException,
			InvocationTargetException {
		Collections.sort(list,new Comparator<ITemperaturePoint>(){
			public int compare(ITemperaturePoint i1, ITemperaturePoint i2) {
				return i1.getHouseNo().compareTo(i2.getHouseNo());
			}
		});
		TemperatureHousePojo tpo = null;
		ITemperaturePointDataGather iTDateGather = null;
		//前台显示温度点数据的集合 houseNo  Hour*Value
		List<TemperatureHousePojo> topList = new ArrayList<TemperatureHousePojo>();
		List<ITemperaturePointDataGather> iTempP = new ArrayList<ITemperaturePointDataGather>();
		this.recordTime = this.recordDate;
		for (ITemperaturePoint iT : list) {
		    tpo = new TemperatureHousePojo();
		    ArrayList<Double> temps = new ArrayList<Double>();
		    tpo.setHouseNo(iT.getHouseNo());
		    //根据温度点编号、所属集中器号、抄表时间查询温度点数据的唯一记录
		    iTDateGather = this.iTemperaturePointDataGatherService.queryUniqueTempPointData(iT.getSeriousNum(), iT.getConcentratorNo(), recordTime);
		    if(iTDateGather != null){
		    	methodGet(tpo, iTDateGather, temps);
		    }
		    iTempP.add(iTDateGather);
		    topList.add(tpo);
		    tpo = null;
		    iTDateGather = null;
		}
		return topList;
	}


	
	
	
	
	public void FTPLogin(){
		hostname = "192.168.1.230";// FTP服务器地址
		port = 2121;// FTP端口号
		username = "test";// FTP用户名
		password = "test";// FTP密码
		String projectNames = new String(projectNameString);
		String commnityNames = new String(filetreeNodeName);
		pathname = "/" + projectNames + "/" + commnityNames;
		localpath = null;//下载后的文件路径
	}
	//下载js文件
	public void downloadFiles(){
		FTPLogin();
		// 文件名称
		String filename = "builDingXY.js";
		str = "";
		InputStream downFile = FavFTPUtil.downloadFile(hostname, port, username, password, pathname, filename, localpath);
		try {
			InputStreamReader isr = new InputStreamReader(downFile,"GBK");
			BufferedReader reader = new BufferedReader(isr);
			StringBuffer sb = new StringBuffer("");
			while((str = reader.readLine()) != null){
			    sb.append(str).append("\n");
			}
			str = sb.toString();
			System.out.println(str);
			downFile.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	// 下载图片
	public void downloadPNG(){
		FTPLogin();
		// 文件名称
		String filename = "community.png";
		FavFTPUtil.downloadPNG(hostname, port,
				username, password, pathname, filename, localpath);
	}
	
	
	
	
	
	
	
	
	
	public String getProjectNameString() {
		return projectNameString;
	}
	public void setProjectNameString(String projectNameString) {
		this.projectNameString = projectNameString;
	}
	public String getRoomHeatDate() {
		return roomHeatDate;
	}
	public void setRoomHeatDate(String roomHeatDate) {
		this.roomHeatDate = roomHeatDate;
	}
	public double getRoomHeatAreaSum() {
		return roomHeatAreaSum;
	}
	public void setRoomHeatAreaSum(double roomHeatAreaSum) {
		this.roomHeatAreaSum = roomHeatAreaSum;
	}
	public IBaseStatisService getiBaseStatisService() {
		return iBaseStatisService;
	}
	public void setiBaseStatisService(IBaseStatisService iBaseStatisService) {
		this.iBaseStatisService = iBaseStatisService;
	}
	public String getFiletreeNodeName() {
		return filetreeNodeName;
	}
	public void setFiletreeNodeName(String filetreeNodeName) {
		this.filetreeNodeName = filetreeNodeName;
	}
	public String getStr() {
		return str;
	}
	public void setStr(String str) {
		this.str = str;
	}
	public String getHostname() {
		return hostname;
	}
	public void setHostname(String hostname) {
		this.hostname = hostname;
	}
	public int getPort() {
		return port;
	}
	public void setPort(int port) {
		this.port = port;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getPathname() {
		return pathname;
	}
	public void setPathname(String pathname) {
		this.pathname = pathname;
	}
	public String getLocalpath() {
		return localpath;
	}
	public void setLocalpath(String localpath) {
		this.localpath = localpath;
	}
	public List<String> getHouseDateList() {
		return houseDateList;
	}
	public void setHouseDateList(List<String> houseDateList) {
		this.houseDateList = houseDateList;
	}
	public List<String> getCommtList() {
		return commtList;
	}
	public void setCommtList(List<String> commtList) {
		this.commtList = commtList;
	}
	public String getMeterNo() {
		return meterNo;
	}
	public void setMeterNo(String meterNo) {
		this.meterNo = meterNo;
	}
	public ICommunityService getiCommunityService() {
		return iCommunityService;
	}
	public void setiCommunityService(ICommunityService iCommunityService) {
		this.iCommunityService = iCommunityService;
	}
	public IBuildingService getiBuildingService() {
		return iBuildingService;
	}
	public void setiBuildingService(IBuildingService iBuildingService) {
		this.iBuildingService = iBuildingService;
	}
	public List<TemperatureMeterDataPojo> getTempMeterList() {
		return tempMeterList;
	}
	public void setTempMeterList(List<TemperatureMeterDataPojo> tempMeterList) {
		this.tempMeterList = tempMeterList;
	}
	public Date getRecordTimeStart() {
		return recordTimeStart;
	}
	public void setRecordTimeStart(Date recordTimeStart) {
		this.recordTimeStart = this.recordDate;
	}
	public Date getRecordTimeEnd() {
		return recordTimeEnd;
	}
	public void setRecordTimeEnd(Date recordTimeEnd) {
		this.recordTimeEnd = this.recordDate;
	}
	public String getShareAreaUID() {
		return shareAreaUID;
	}
	public void setShareAreaUID(String shareAreaUID) {
		this.shareAreaUID = shareAreaUID;
	}
	public String getConcentratorNo() {
		return concentratorNo;
	}
	public void setConcentratorNo(String concentratorNo) {
		this.concentratorNo = concentratorNo;
	}
	public Date getRecordTime() {
		return recordTime;
	}
	public void setRecordTime(Date recordTime) {
		this.recordTime = recordTime;
	}
	public String getSeriousNum() {
		return seriousNum;
	}
	public void setSeriousNum(String seriousNum) {
		this.seriousNum = seriousNum;
	}
	public String getConcentratorUID() {
		return concentratorUID;
	}
	public void setConcentratorUID(String concentratorUID) {
		this.concentratorUID = concentratorUID;
	}
	public PageCond getPageCond() {
		return pageCond;
	}
	public void setPageCond(PageCond pageCond) {
		this.pageCond = pageCond;
	}
	public IHeatMeterDataGatherService getiHeatMeterDataGatherService() {
		return iHeatMeterDataGatherService;
	}
	public void setiHeatMeterDataGatherService(
			IHeatMeterDataGatherService iHeatMeterDataGatherService) {
		this.iHeatMeterDataGatherService = iHeatMeterDataGatherService;
	}
	public IHeatMeterService getiHeatMeterService() {
		return iHeatMeterService;
	}
	public void setiHeatMeterService(IHeatMeterService iHeatMeterService) {
		this.iHeatMeterService = iHeatMeterService;
	}
	public ITemperaturePointService getiTemperaturePointService() {
		return iTemperaturePointService;
	}
	public void setiTemperaturePointService(
			ITemperaturePointService iTemperaturePointService) {
		this.iTemperaturePointService = iTemperaturePointService;
	}
	public ITemperaturePointDataGatherService getiTemperaturePointDataGatherService() {
		return iTemperaturePointDataGatherService;
	}
	public void setiTemperaturePointDataGatherService(
			ITemperaturePointDataGatherService iTemperaturePointDataGatherService) {
		this.iTemperaturePointDataGatherService = iTemperaturePointDataGatherService;
	}
	public Date getRecordDate() {
		return recordDate;
	}
	public void setRecordDate(Date recordDate) {
		this.recordDate = recordDate;
	}
	public String getProjectUID() {
		return projectUID;
	}
	public void setProjectUID(String projectUID) {
		this.projectUID = projectUID;
	}
	public String getCommunityUID() {
		return communityUID;
	}
	public void setCommunityUID(String communityUID) {
		this.communityUID = communityUID;
	}
	public String getBuildingUID() {
		return buildingUID;
	}
	public void setBuildingUID(String buildingUID) {
		this.buildingUID = buildingUID;
	}
	public String getPointData() {
		return pointData;
	}
	public void setPointData(String pointData) {
		this.pointData = pointData;
	}
	public String getMeterNo1() {
		return meterNo1;
	}
	public void setMeterNo1(String meterNo1) {
		this.meterNo1 = meterNo1;
	}
	public String getMeterNo2() {
		return meterNo2;
	}
	public void setMeterNo2(String meterNo2) {
		this.meterNo2 = meterNo2;
	}
}
